﻿using System;
using System.Collections;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace FRS_LIB.Devices
{
    public class SwitchBox : DeviceBase
    {
        private const int PORT = 2701;
        private const int OUTPUTS = 14;

        public SwitchBox(Device device)
            : this(device.Address, device.Name)
        {
        }

        public SwitchBox(string address, string name) 
            : base(address, name)
        {
            base.TcpSendreceive(String.Format("!io get port 2\n"), PORT);
        }

        public override bool GetOutput(int outputNr)
        {
            Boolean result = false;
            
            if (outputNr < 6)
            {
                string response = base.TcpSendreceive(String.Format("!io get port 2\n"), PORT);
                Console.WriteLine("{0}", response);
                if ((Convert.ToUInt32(response.Substring(10, 2), 16) & 1 << outputNr) == 1 << outputNr)
                {
                    result = true;
                }
            }
            else
            {
                string response = base.TcpSendreceive(String.Format("!io get port 3\n"), PORT);
                Console.WriteLine("{0}", response);
                if ((Convert.ToUInt32(response.Substring(10, 2), 16) & 1 << outputNr-6) == 1 << outputNr-6)
                {
                    result = true;
                }
            }
            return result;
        }

        public override void SetOutput(int outputNr, int value)
        {
            if (outputNr > OUTPUTS - 1)
                throw new Exception(String.Format("Device has only {1} ports!", OUTPUTS));

            int port = outputNr < 6 ? 2 : 3;
            int portPin = outputNr < 6 ? outputNr : outputNr - 6;
            string result = base.TcpSendreceive(String.Format("!io set port {0:d} {1:x2} {2:x2}\n", port, (int)Math.Pow(2, portPin) * value, (int)Math.Pow(2, portPin)), PORT);
            Console.WriteLine("{0}", result);
        }
    }
}
